package com.yd.cfckc.util;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;
import com.alibaba.fastjson.JSONObject;

/**
 * @author cuiyufeng
 * @email cuiyufeng1458@yundasys.com
 * @date 2020/10/16 3:45 下午
 */
public class XmlAnalysis {

    public static void main(String[] args) throws Exception {
        String xml = "<dta st=\"ok\"  op=\"ex03orderlj\"><h><ver>1.0</ver><time>2014-05-15 10:42:29</time></h><data></data></dta>";
        //String xml = "<dta st=\"ok\"  op=\"ex03orderlj\"><h><ver>1.0</ver><time>2014-05-15 10:42:29</time></h><data><o><d>1000225864854</d><d>341000</d><d></d><d>2013-10-06 18:18:37</d></o></data></dta>";
//		long start = System.currentTimeMillis();
//		for (int i = 0; i < 10000; i++) {
//			String[] a = XmlAnalysis.getTags(xml);
//		}
//		System.out.println((System.currentTimeMillis() - start) / 1000.0);
//
//		String[] a = XmlAnalysis.getTags(xml);
//		System.out.println(a[0]);
//		System.out.println(a[1]);
//		System.out.println(a[2]);
//		System.out.println(a[3]);
//		System.out.println(a[4]);
//		System.out.println(a[5]);
//		System.out.println(a[6]);
        System.out.println(JSONObject.toJSONString(XmlAnalysis.getTagAllValue(xml,"d")));
    }

    /**
     * 查询指定xml文件标签对应的属性
     *
     * @param sXML
     * @param sTag
     * @param sAttr
     * @return
     * @throws Exception
     */
    public static String getAttribute(String sXML, String sTag, String sAttr)
            throws Exception {
        QName qTag = new QName(sTag);
        QName qAttr = new QName(sAttr);
        String sRet = "";
        StringReader sReader = new StringReader(sXML);
        XMLInputFactory xFactory = XMLInputFactory.newInstance();
        XMLStreamReader xReader;
        for (xReader = xFactory.createXMLStreamReader(sReader); xReader
                .hasNext();) {
            int event = xReader.next();
            if (event == 1 && xReader.getName().equals(qTag)) {
                sRet = xReader.getAttributeValue(null, qAttr.getLocalPart());
                break;
            }
        }
        xReader.close();
        return sRet;
    }

    /**
     * 查询指定xml文件对应标签的内容
     *
     * @param sXML
     * @param sTag
     * @return
     * @throws Exception
     */
    public static String getTagFirstValue(String sXML, String sTag)
            throws Exception {
        QName qTag = new QName(sTag);
        String sRet = "";
        StringReader sReader = new StringReader(sXML);
        XMLInputFactory xFactory = XMLInputFactory.newInstance();
        XMLStreamReader xReader;
        for (xReader = xFactory.createXMLStreamReader(sReader); xReader
                .hasNext();) {
            int event = xReader.next();
            if (event == 1 && xReader.getName().equals(qTag)) {
                sRet = xReader.getElementText();
                break;
            }
        }
        xReader.close();
        return sRet;
    }

    /**
     * 查询指定xml文件对应标签的内容
     *
     * @param sXML
     * @param sTag
     * @return
     * @throws Exception
     */
    public static String[] getTagAllValue(String sXML, String sTag)
            throws Exception {
        QName qTag = new QName(sTag);
        StringBuffer buffer = new StringBuffer();
        StringReader sReader = new StringReader(sXML);
        XMLInputFactory xFactory = XMLInputFactory.newInstance();
        XMLStreamReader xReader;
        for (xReader = xFactory.createXMLStreamReader(sReader); xReader
                .hasNext();) {
            int event = xReader.next();
            if (event == 1 && xReader.getName().equals(qTag)) {
                buffer.append(",").append(xReader.getElementText());
            }
        }
        xReader.close();
        if(buffer.length() > 0 ){
            return buffer.toString().substring(1).split(",");
        }
        return new String[]{};
    }


    /**
     * 查询指定xml文件对应标签的内容
     *
     * @param sXML
     * @param sTag
     * @return
     * @throws Exception
     */
    public static String[] getTagAllZLValue(String sXML, String sTag)
            throws Exception {
        QName qTag = new QName(sTag);
        StringBuffer buffer = new StringBuffer();
        StringReader sReader = new StringReader(sXML);
        XMLInputFactory xFactory = XMLInputFactory.newInstance();
        XMLStreamReader xReader;
        for (xReader = xFactory.createXMLStreamReader(sReader); xReader
                .hasNext();) {
            int event = xReader.next();
            if (event == 1 && xReader.getName().equals(qTag)) {
                buffer.append("@").append(xReader.getElementText());
            }
        }
        xReader.close();
        if(buffer.length() > 0 ){
            return buffer.toString().substring(1).split("@");
        }
        return new String[]{};
    }


    public static String[] getTags(String sXML) throws Exception {
        QName qAttr = new QName("op");
        QName qTag0 = new QName("req");
        QName qTag1 = new QName("ver");
        QName qTag2 = new QName("company");
        QName qTag3 = new QName("user");
        QName qTag4 = new QName("pass");
        QName qTag5 = new QName("dev1");
        QName qTag6 = new QName("dev2");
        QName qTag7 = new QName("type");
        String[] aRet = new String[8];

        StringReader sReader = new StringReader(sXML);
        XMLInputFactory xFactory = XMLInputFactory.newInstance();
        XMLStreamReader xReader;
        for (xReader = xFactory.createXMLStreamReader(sReader); xReader
                .hasNext();) {
            int event = xReader.next();
            if (event == 1) {
                if (xReader.getName().equals(qTag0)) {
                    aRet[0] = xReader.getAttributeValue(null, qAttr
                            .getLocalPart());
                } else if (xReader.getName().equals(qTag1)) {
                    aRet[1] = xReader.getElementText();
                } else if (xReader.getName().equals(qTag2)) {
                    aRet[2] = xReader.getElementText();
                } else if (xReader.getName().equals(qTag3)) {
                    aRet[3] = xReader.getElementText();
                } else if (xReader.getName().equals(qTag4)) {
                    aRet[4] = xReader.getElementText();
                } else if (xReader.getName().equals(qTag5)) {
                    aRet[5] = xReader.getElementText();
                } else if (xReader.getName().equals(qTag6)) {
                    aRet[6] = xReader.getElementText();
                } else if (xReader.getName().equals(qTag7)) {
                    aRet[7] = xReader.getElementText();
                }
            }
        }
        xReader.close();
        return aRet;
    }

    /**
     * 通过xsd校验xml内容
     *
     * @param xmlContent
     * @param xsdFileName
     * @return
     */
    public static int validateXMLByXSD(String xmlContent, String xsdFileName) {
        try {
            /*
             * // 1 factory SAXParserFactory factory =
             * SAXParserFactory.newInstance(); factory.setValidating(true);
             * factory.setNamespaceAware(true); SAXParser parser =
             * factory.newSAXParser(); parser.setProperty(
             * "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
             * "http://www.w3.org/2001/XMLSchema"); parser.setProperty(
             * "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" +
             * xsdFileName);
             *  // 2 reader Document xmlDocument =
             * DocumentHelper.parseText(xmlContent);
             *  // 3 validator SAXValidator validator = new
             * SAXValidator(parser.getXMLReader()); XMLErrorHandler errorHandler =
             * new XMLErrorHandler(); validator.setErrorHandler(errorHandler);
             * validator.validate(xmlDocument);
             *  // 4 writer //XMLWriter writer = new
             * XMLWriter(OutputFormat.createPrettyPrint()); if
             * (errorHandler.getErrors().hasContent()) {
             * //System.out.println("XML文件通过XSD文件校验失败！");
             * //writer.write(errorHandler.getErrors()); return 1; } else {
             * //System.out.println("XML文件通过XSD文件校验成功！"); return 0; }
             */
            return 1;

        } catch (Exception ex) {
            // System.out.println("XML文件: " + xml + " 通过XSD文件:"
            // + xsdFileName + "检验失败。\n原因：\n " + ex.getMessage());
            //ex.printStackTrace();

            return 2;
        }
    }
}
